<!DOCTYPE html>













<html class="theme-next gemini" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '6.3.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="如何在 SpringBoot 工程中使用 Atomikos 解决分布式事务的问题。">
<meta name="keywords" content="Mybatis">
<meta property="og:type" content="article">
<meta property="og:title" content="分布式事务管理工具 Atomikos">
<meta property="og:url" content="http://yoursite.com/2018/06/02/MyBatis/多数据源事务管理/index.html">
<meta property="og:site_name" content="Kyou">
<meta property="og:description" content="如何在 SpringBoot 工程中使用 Atomikos 解决分布式事务的问题。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-06-02T09:40:43.300Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分布式事务管理工具 Atomikos">
<meta name="twitter:description" content="如何在 SpringBoot 工程中使用 Atomikos 解决分布式事务的问题。">






  <link rel="canonical" href="http://yoursite.com/2018/06/02/MyBatis/多数据源事务管理/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>分布式事务管理工具 Atomikos | Kyou</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Kyou</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">IT 随笔集</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/blog/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签<span class="badge">9</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类<span class="badge">4</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/blog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档<span class="badge">9</span></a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/2018/06/02/MyBatis/多数据源事务管理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kyou">
      <meta itemprop="description" content="^_^">
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Kyou">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">分布式事务管理工具 Atomikos
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-06-02 14:34:52 / 修改时间：17:40:43" itemprop="dateCreated datePublished" datetime="2018-06-02T14:34:52+08:00">2018-06-02</time>
            

            
              

              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/Java-知识点/" itemprop="url" rel="index"><span itemprop="name">Java 知识点</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          
              <div class="post-description">如何在 SpringBoot 工程中使用 Atomikos 解决分布式事务的问题。</div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p> 当项目涉及多个数据源时,多数据源事务回滚问题的解决方案之一是使用 Atomikos 工具实现分布式事务的管理.</p>
<h4 id="1-Spring-Boot-配置文件"><a href="#1-Spring-Boot-配置文件" class="headerlink" title="1.Spring Boot 配置文件"></a>1.Spring Boot 配置文件</h4><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#数据源1</span></span><br><span class="line">datasource.mysql.smp.url=jdbc:mysql://localhost:3306/smp?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true</span><br><span class="line">datasource.mysql.smp.username=root</span><br><span class="line">datasource.mysql.smp.password=654321`w?</span><br><span class="line">datasource.mysql.smp.driver-class-name=com.mysql.jdbc.Driver</span><br><span class="line"><span class="comment">##下面为连接池的补充设置，应用到上面所有数据源中</span></span><br><span class="line"><span class="comment">##初始化大小，最小，最大</span></span><br><span class="line">datasource.mysql.smp.initialSize=5</span><br><span class="line"><span class="comment">#连接池最小空闲线程数(一般不必配置)</span></span><br><span class="line"><span class="comment">#datasource.mysql.smp.minIdle=5</span></span><br><span class="line"><span class="comment">#连接池最大连接数(小于连接池的大小时可能出现访问数据异常)</span></span><br><span class="line">datasource.mysql.smp.maxActive=100</span><br><span class="line"><span class="comment">##配置获取连接等待超时的时间(毫秒)</span></span><br><span class="line">datasource.mysql.smp.maxWait=30000</span><br><span class="line"><span class="comment">##配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒</span></span><br><span class="line">datasource.mysql.smp.timeBetweenEvictionRunsMillis=30000</span><br><span class="line"><span class="comment">##配置一个连接在池中最小生存的时间，单位是毫秒</span></span><br><span class="line">datasource.mysql.smp.minEvictableIdleTimeMillis=60000</span><br><span class="line">datasource.mysql.smp.validationQuery=SELECT 1</span><br><span class="line">datasource.mysql.smp.validationQueryTimeout=10000</span><br><span class="line">datasource.mysql.smp.testWhileIdle=true</span><br><span class="line">datasource.mysql.smp.testOnBorrow=false</span><br><span class="line">datasource.mysql.smp.testOnReturn=false</span><br><span class="line"><span class="comment">##打开PSCache，并且指定每个连接上PSCache的大小</span></span><br><span class="line">datasource.mysql.smp.poolPreparedStatements=true</span><br><span class="line"><span class="comment">#预处理 SQL 的连接数</span></span><br><span class="line">datasource.mysql.smp.maxPoolPreparedStatementPerConnectionSize=20</span><br><span class="line">datasource.mysql.smp.filters=stat,wall,log4j</span><br><span class="line"><span class="comment">##通过connectProperties属性来打开mergeSql功能；慢SQL记录</span></span><br><span class="line">datasource.mysql.smp.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000</span><br><span class="line"></span><br><span class="line"><span class="comment">#数据源2</span></span><br><span class="line">datasource.mysql.mydb.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true</span><br><span class="line">datasource.mysql.mydb.username=root</span><br><span class="line">datasource.mysql.mydb.password=654321`w?</span><br><span class="line">datasource.mysql.mydb.driver-class-name=com.mysql.jdbc.Driver</span><br><span class="line"><span class="comment">##下面为连接池的补充设置，应用到上面所有数据源中</span></span><br><span class="line"><span class="comment">##初始化大小，最小，最大</span></span><br><span class="line">datasource.mysql.mydb.initialSize=5</span><br><span class="line">datasource.mysql.mydb.minIdle=5</span><br><span class="line">datasource.mysql.mydb.maxActive=20</span><br><span class="line"><span class="comment">##配置获取连接等待超时的时间</span></span><br><span class="line">datasource.mysql.mydb.maxWait=60000v</span><br><span class="line"><span class="comment">##配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒</span></span><br><span class="line">datasource.mysql.mydb.timeBetweenEvictionRunsMillis=60000</span><br><span class="line"><span class="comment">##配置一个连接在池中最小生存的时间，单位是毫秒</span></span><br><span class="line">datasource.mysql.mydb.minEvictableIdleTimeMillis=60000</span><br><span class="line">datasource.mysql.mydb.validationQuery=SELECT 1</span><br><span class="line">datasource.mysql.mydb.validationQueryTimeout=10000</span><br><span class="line">datasource.mysql.mydb.testWhileIdle=true</span><br><span class="line">datasource.mysql.mydb.testOnBorrow=false</span><br><span class="line">datasource.mysql.mydb.testOnReturn=false</span><br><span class="line"><span class="comment">##打开PSCache，并且指定每个连接上PSCache的大小</span></span><br><span class="line">datasource.mysql.mydb.poolPreparedStatements=true</span><br><span class="line">datasource.mysql.mydb.maxPoolPreparedStatementPerConnectionSize=20</span><br><span class="line">datasource.mysql.mydb.filters=stat,wall,log4j</span><br><span class="line"><span class="comment">##通过connectProperties属性来打开mergeSql功能；慢SQL记录</span></span><br><span class="line">datasource.mysql.mydb.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000</span><br></pre></td></tr></table></figure>
<h4 id="2-自定义数据源1"><a href="#2-自定义数据源1" class="headerlink" title="2.自定义数据源1"></a>2.自定义数据源1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.ok.mybatisdemo.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atomikos.jdbc.AtomikosDataSourceBean;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;</span><br><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionFactoryBean;</span><br><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionTemplate;</span><br><span class="line"><span class="keyword">import</span> org.mybatis.spring.annotation.MapperScan;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.env.Environment;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.sql.DataSource;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kyou on 2018/2/4 15:58</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@MapperScan</span>(basePackages = <span class="string">"cn.ok.mybatisdemo.mapper.mydb"</span>, sqlSessionTemplateRef = <span class="string">"MydbSqlSessionTemplate"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MydbDataSource</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 指定的 Bean name 跟方法名不能一样</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 数据源对象</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"MydbDataSource"</span>)</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">systemDataSource</span><span class="params">(Environment env)</span> </span>&#123;</span><br><span class="line">        AtomikosDataSourceBean atomikosDataSource = <span class="keyword">new</span> AtomikosDataSourceBean();</span><br><span class="line">        Properties prop = SmpDataSource.getDataSourceProperties(env, <span class="string">"datasource.mysql.mydb."</span>);</span><br><span class="line">        atomikosDataSource.setXaDataSourceClassName(<span class="string">"com.alibaba.druid.pool.xa.DruidXADataSource"</span>);</span><br><span class="line">        atomikosDataSource.setUniqueResourceName(<span class="string">"MydbDB"</span>);</span><br><span class="line">        atomikosDataSource.setMinPoolSize(<span class="number">5</span>);</span><br><span class="line">        atomikosDataSource.setMaxPoolSize(<span class="number">20</span>);</span><br><span class="line">        atomikosDataSource.setXaProperties(prop);</span><br><span class="line">        <span class="keyword">return</span> atomikosDataSource;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"MydbSqlSessionFactory"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">mydbSqlSessionFactory</span><span class="params">(@Qualifier(<span class="string">"MydbDataSource"</span>)</span> DataSource dataSource) <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        SqlSessionFactoryBean bean = <span class="keyword">new</span> SqlSessionFactoryBean();</span><br><span class="line">        bean.setDataSource(dataSource);</span><br><span class="line">        <span class="comment">// 下划线(数据库字段) 转 驼峰(业务对象)</span></span><br><span class="line">        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> bean.getObject();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"MydbSqlSessionTemplate"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionTemplate <span class="title">mydbSqlSessionTemplate</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            @Qualifier(<span class="string">"MydbSqlSessionFactory"</span>)</span> SqlSessionFactory sqlSessionFactory) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SqlSessionTemplate(sqlSessionFactory);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="3-自定义数据源2"><a href="#3-自定义数据源2" class="headerlink" title="3.自定义数据源2"></a>3.自定义数据源2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.ok.mybatisdemo.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atomikos.jdbc.AtomikosDataSourceBean;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;</span><br><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionFactoryBean;</span><br><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionTemplate;</span><br><span class="line"><span class="keyword">import</span> org.mybatis.spring.annotation.MapperScan;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Primary;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.env.Environment;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.sql.DataSource;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 通过 basePackages 属性不同的数据源扫描不同包下的 Mapper.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kyou on 2018/2/4 15:58</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@MapperScan</span>(basePackages = <span class="string">"cn.ok.mybatisdemo.mapper.smp"</span>, sqlSessionTemplateRef = <span class="string">"SmpSqlSessionTemplate"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmpDataSource</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Properties <span class="title">getDataSourceProperties</span><span class="params">(Environment env, String prefix)</span> </span>&#123;</span><br><span class="line">        Properties prop = <span class="keyword">new</span> Properties();</span><br><span class="line">        prop.put(<span class="string">"url"</span>, env.getProperty(prefix + <span class="string">"url"</span>));</span><br><span class="line">        prop.put(<span class="string">"username"</span>, env.getProperty(prefix + <span class="string">"username"</span>));</span><br><span class="line">        prop.put(<span class="string">"password"</span>, env.getProperty(prefix + <span class="string">"password"</span>));</span><br><span class="line">        prop.put(<span class="string">"driverClassName"</span>, env.getProperty(prefix + <span class="string">"driverClassName"</span>, <span class="string">""</span>));</span><br><span class="line">        prop.put(<span class="string">"initialSize"</span>, env.getProperty(prefix + <span class="string">"initialSize"</span>, Integer.class));</span><br><span class="line">        prop.put(<span class="string">"maxActive"</span>, env.getProperty(prefix + <span class="string">"maxActive"</span>, Integer.class));</span><br><span class="line">        <span class="comment">// prop.put("minIdle", env.getProperty(prefix + "minIdle", Integer.class));</span></span><br><span class="line">        prop.put(<span class="string">"maxWait"</span>, env.getProperty(prefix + <span class="string">"maxWait"</span>, Integer.class));</span><br><span class="line">        prop.put(<span class="string">"timeBetweenEvictionRunsMillis"</span>,</span><br><span class="line">                env.getProperty(prefix + <span class="string">"timeBetweenEvictionRunsMillis"</span>, Integer.class));</span><br><span class="line">        prop.put(<span class="string">"minEvictableIdleTimeMillis"</span>, env.getProperty(prefix + <span class="string">"minEvictableIdleTimeMillis"</span>, Integer.class));</span><br><span class="line"></span><br><span class="line">        prop.put(<span class="string">"validationQuery"</span>, env.getProperty(prefix + <span class="string">"validationQuery"</span>));</span><br><span class="line">        prop.put(<span class="string">"validationQueryTimeout"</span>, env.getProperty(prefix + <span class="string">"validationQueryTimeout"</span>, Integer.class));</span><br><span class="line">        prop.put(<span class="string">"testWhileIdle"</span>, env.getProperty(prefix + <span class="string">"testWhileIdle"</span>, Boolean.class));</span><br><span class="line">        prop.put(<span class="string">"testOnBorrow"</span>, env.getProperty(prefix + <span class="string">"testOnBorrow"</span>, Boolean.class));</span><br><span class="line">        prop.put(<span class="string">"testOnReturn"</span>, env.getProperty(prefix + <span class="string">"testOnReturn"</span>, Boolean.class));</span><br><span class="line"></span><br><span class="line">        prop.put(<span class="string">"poolPreparedStatements"</span>, env.getProperty(prefix + <span class="string">"poolPreparedStatements"</span>, Boolean.class));</span><br><span class="line">        prop.put(<span class="string">"maxPoolPreparedStatementPerConnectionSize"</span>,</span><br><span class="line">                env.getProperty(prefix + <span class="string">"maxPoolPreparedStatementPerConnectionSize"</span>, Integer.class));</span><br><span class="line">        prop.put(<span class="string">"filters"</span>, env.getProperty(prefix + <span class="string">"filters"</span>));</span><br><span class="line">        prop.put(<span class="string">"connectionProperties"</span>, env.getProperty(prefix + <span class="string">"connectionProperties"</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> prop;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 指定的 Bean name 跟方法名不能一样</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 数据源对象</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"SmpDataSource"</span>)</span><br><span class="line">    <span class="meta">@Primary</span></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">systemDataSource</span><span class="params">(Environment env)</span> </span>&#123;</span><br><span class="line">        AtomikosDataSourceBean atomikosDataSource = <span class="keyword">new</span> AtomikosDataSourceBean();</span><br><span class="line">        Properties prop = getDataSourceProperties(env, <span class="string">"datasource.mysql.smp."</span>);</span><br><span class="line">        atomikosDataSource.setXaDataSourceClassName(<span class="string">"com.alibaba.druid.pool.xa.DruidXADataSource"</span>);</span><br><span class="line">        atomikosDataSource.setUniqueResourceName(<span class="string">"SmpDB"</span>);</span><br><span class="line">        <span class="comment">// 连接池大小</span></span><br><span class="line">        atomikosDataSource.setMinPoolSize(<span class="number">5</span>);</span><br><span class="line">        atomikosDataSource.setMaxPoolSize(<span class="number">20</span>);</span><br><span class="line">        atomikosDataSource.setXaProperties(prop);</span><br><span class="line">        <span class="keyword">return</span> atomikosDataSource;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"SmpSqlSessionFactory"</span>)</span><br><span class="line">    <span class="meta">@Primary</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">smpSqlSessionFactory</span><span class="params">(@Qualifier(<span class="string">"SmpDataSource"</span>)</span> DataSource dataSource) <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        SqlSessionFactoryBean bean = <span class="keyword">new</span> SqlSessionFactoryBean();</span><br><span class="line">        bean.setDataSource(dataSource);</span><br><span class="line">        <span class="comment">// 下划线(数据库字段) 转 驼峰(业务对象)</span></span><br><span class="line">        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> bean.getObject();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"SmpSqlSessionTemplate"</span>)</span><br><span class="line">    <span class="meta">@Primary</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionTemplate <span class="title">smpSqlSessionTemplate</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            @Qualifier(<span class="string">"SmpSqlSessionFactory"</span>)</span> SqlSessionFactory sqlSessionFactory) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SqlSessionTemplate(sqlSessionFactory);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-自定义事务管理器"><a href="#4-自定义事务管理器" class="headerlink" title="4.自定义事务管理器"></a>4.自定义事务管理器</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.ok.mybatisdemo.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atomikos.icatch.jta.UserTransactionImp;</span><br><span class="line"><span class="keyword">import</span> com.atomikos.icatch.jta.UserTransactionManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.transaction.PlatformTransactionManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.transaction.annotation.EnableTransactionManagement;</span><br><span class="line"><span class="keyword">import</span> org.springframework.transaction.interceptor.TransactionInterceptor;</span><br><span class="line"><span class="keyword">import</span> org.springframework.transaction.jta.JtaTransactionManager;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.transaction.TransactionManager;</span><br><span class="line"><span class="keyword">import</span> javax.transaction.UserTransaction;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kyou on 2018/2/4 15:58</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TransactionManagerConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"userTransaction"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserTransaction <span class="title">userTransaction</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        UserTransactionImp userTransactionImp = <span class="keyword">new</span> UserTransactionImp();</span><br><span class="line">        userTransactionImp.setTransactionTimeout(<span class="number">10000</span>);</span><br><span class="line">        <span class="keyword">return</span> userTransactionImp;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"atomikosTransactionManager"</span>, initMethod = <span class="string">"init"</span>, destroyMethod = <span class="string">"close"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransactionManager <span class="title">atomikosTransactionManager</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        UserTransactionManager userTransactionManager = <span class="keyword">new</span> UserTransactionManager();</span><br><span class="line">        userTransactionManager.setForceShutdown(<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">return</span> userTransactionManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"transactionManager"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> PlatformTransactionManager <span class="title">transactionManager</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            @Qualifier(<span class="string">"userTransaction"</span>)</span> UserTransaction userTransaction,</span></span><br><span class="line"><span class="function">            @<span class="title">Qualifier</span><span class="params">(<span class="string">"atomikosTransactionManager"</span>)</span> TransactionManager atomikosTransactionManager) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> JtaTransactionManager(userTransaction, atomikosTransactionManager);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"transactionInterceptor"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransactionInterceptor <span class="title">transactionInterceptor</span><span class="params">(PlatformTransactionManager platformTransactionManager)</span> </span>&#123;</span><br><span class="line">        TransactionInterceptor transactionInterceptor = <span class="keyword">new</span> TransactionInterceptor();</span><br><span class="line">        <span class="comment">// 事物管理器</span></span><br><span class="line">        transactionInterceptor.setTransactionManager(platformTransactionManager);</span><br><span class="line">        Properties transactionAttributes = <span class="keyword">new</span> Properties();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// test</span></span><br><span class="line">        transactionAttributes.setProperty(<span class="string">"test*"</span>, <span class="string">"PROPAGATION_REQUIRED,-Throwable"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 新增</span></span><br><span class="line">        transactionAttributes.setProperty(<span class="string">"insert*"</span>, <span class="string">"PROPAGATION_REQUIRED,-Throwable"</span>);</span><br><span class="line">        <span class="comment">// 修改</span></span><br><span class="line"></span><br><span class="line">        transactionAttributes.setProperty(<span class="string">"update*"</span>, <span class="string">"PROPAGATION_REQUIRED,-Throwable"</span>);</span><br><span class="line">        <span class="comment">// 删除</span></span><br><span class="line">        transactionAttributes.setProperty(<span class="string">"delete*"</span>, <span class="string">"PROPAGATION_REQUIRED,-Throwable"</span>);</span><br><span class="line">        <span class="comment">// 查询</span></span><br><span class="line">        transactionAttributes.setProperty(<span class="string">"select*"</span>, <span class="string">"PROPAGATION_REQUIRED,-Throwable,readOnly"</span>);</span><br><span class="line"></span><br><span class="line">        transactionInterceptor.setTransactionAttributes(transactionAttributes);</span><br><span class="line">        <span class="keyword">return</span> transactionInterceptor;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-操作数据源1"><a href="#5-操作数据源1" class="headerlink" title="5.操作数据源1"></a>5.操作数据源1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.ok.mybatisdemo.mapper.mydb;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> cn.ok.mybatisdemo.entity.User;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Insert;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Mapper;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Select;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kyou on 2018/2/4 17:14</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">MydbUserMapper</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询用户信息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 用户</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Select</span>(<span class="string">"SELECT * FROM USER"</span>)</span><br><span class="line">    <span class="function">List&lt;User&gt; <span class="title">doSelect</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 插入数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 影响行数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Insert</span>(<span class="string">"INSERT INTO USER (USER_NAME,PASSWORD) VALUES (\"AA1\",\"AA1\")"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">doInsert</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="6-操作数据源2"><a href="#6-操作数据源2" class="headerlink" title="6.操作数据源2"></a>6.操作数据源2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.ok.mybatisdemo.mapper.smp;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> cn.ok.mybatisdemo.entity.User;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Insert;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Mapper;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Select;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kyou on 2018/2/4 16:24</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">SmpUserMapper</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询用户信息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 用户</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Select</span>(<span class="string">"SELECT * FROM USER"</span>)</span><br><span class="line">    <span class="function">List&lt;User&gt; <span class="title">doSelect</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 插入数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 影响行数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Insert</span>(<span class="string">"INSERT INTO USER (USER_NAME,PASSWORD) VALUES (\"AA1\",\"AA1\")"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">doInsert</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="7-事务管理示例"><a href="#7-事务管理示例" class="headerlink" title="7.事务管理示例"></a>7.事务管理示例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.ok.mybatisdemo.controller;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> cn.ok.mybatisdemo.entity.User;</span><br><span class="line"><span class="keyword">import</span> cn.ok.mybatisdemo.mapper.mydb.MydbUserMapper;</span><br><span class="line"><span class="keyword">import</span> cn.ok.mybatisdemo.mapper.smp.SmpUserMapper;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.transaction.TransactionManager;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kyou on 2018/2/4 14:25</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MydbUserMapper mydbUserMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> SmpUserMapper smpUserMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span>(required = <span class="keyword">false</span>)</span><br><span class="line">    <span class="keyword">private</span> TransactionManager transactionManager;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RequestMapping</span>(<span class="string">"insert"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">doInsert</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        log.debug(<span class="string">"开始============="</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            transactionManager.begin();</span><br><span class="line"></span><br><span class="line">            smpUserMapper.doInsert();</span><br><span class="line">            log.debug(<span class="string">"插入1============="</span>);</span><br><span class="line"></span><br><span class="line">            mydbUserMapper.doInsert();</span><br><span class="line">            log.debug(<span class="string">"插入2============="</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// get a NullPointerException</span></span><br><span class="line">            User user = <span class="keyword">null</span>;</span><br><span class="line">            <span class="comment">//noinspection ConstantConditions</span></span><br><span class="line">            log.debug(user.getUserName());</span><br><span class="line">            log.debug(<span class="string">"完成============="</span>);</span><br><span class="line"></span><br><span class="line">            transactionManager.commit();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NullPointerException e) &#123;</span><br><span class="line">            log.debug(<span class="string">"回滚============="</span>);</span><br><span class="line">            transactionManager.rollback();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        log.debug(<span class="string">"End============="</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"END."</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Mybatis/" rel="tag"># Mybatis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/06/02/MyBatis/最简单的方式(注解)/" rel="prev" title="最简单的集成 mybatis 的方式">
                最简单的集成 mybatis 的方式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Kyou</p>
              <p class="site-description motion-element" itemprop="description">^_^</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/blog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/wgoodq" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:wcupq@foxmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-Spring-Boot-配置文件"><span class="nav-number">1.</span> <span class="nav-text">1.Spring Boot 配置文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-自定义数据源1"><span class="nav-number">2.</span> <span class="nav-text">2.自定义数据源1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-自定义数据源2"><span class="nav-number">3.</span> <span class="nav-text">3.自定义数据源2</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-自定义事务管理器"><span class="nav-number">4.</span> <span class="nav-text">4.自定义事务管理器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-操作数据源1"><span class="nav-number">5.</span> <span class="nav-text">5.操作数据源1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-操作数据源2"><span class="nav-number">6.</span> <span class="nav-text">6.操作数据源2</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-事务管理示例"><span class="nav-number">7.</span> <span class="nav-text">7.事务管理示例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kyou</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.3.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
